﻿#include "guild_service_chat_context.h"

#include "box/service_context.hh"
// #include "error/make_error_code.h"
#include "fwd.h"

#include "guild/guild.h"

namespace guild_service {
bool GuildServiceChatContext::Start(kratos::service::ServiceContext *context) {
  if (!GuildServiceChatContext::Init(context)) {
    LOG_FAIL("公会聊天服务启动失败");
    return false;
  }

  return register_service(std::string(kGuildServicePrefix) + std::string(kGuildServiceChatName));
}

bool GuildServiceChatContext::Stop() {
  LOG_INFO("公会聊天服务关闭");

  if (!unregister_service(std::string(kGuildServicePrefix) +
                          std::string(kGuildServiceChatName))) {
    LOG_FAIL("公会聊天服务关闭失败");
    return false;
  }

  return GuildServiceChatContext::Uninit();
}

bool GuildServiceChatContext::Init(kratos::service::ServiceContext *context) {
  if (!context) {
    return false;
  }

  if (!common::singleton_start<common::service_logger>(
          context, kGuildServiceChatName)) {
    return false;
  }

  LOG_INFO("公会聊天服务启动");

  if (!common::singleton_start<common::service_context>(context)) {
    LOG_FAIL("公会聊天服务启动失败");
    return false;
  }

  if (!common::singleton_start<common::service_redis_client>(context)) {
    LOG_FAIL("公会聊天服务启动失败");
    return false;
  }

  std::string redis_host(kRedisHost);
  int32_t redis_port = kRedisPort;
  std::string redis_user(kRedisUser);
  std::string redis_passwd(kRedisPasswd);
  
  {  // config.redis
    auto *config_ptr = ServiceContextSingleton()->get_config().get_config_ptr();
    if (!config_ptr) {
      LOG_FAIL("公会认证服务启动失败");
      return false;
    }
    if (config_ptr->has("redis")) {
      if (config_ptr->has("redis.host")) {
        redis_host = config_ptr->getString("redis.host");
      }
      if (config_ptr->has("redis.port")) {
        redis_port = config_ptr->getInt32("redis.port");
      }
      if (config_ptr->has("redis.user")) {
        redis_user = config_ptr->getString("redis.user");
      }
      if (config_ptr->has("redis.passwd")) {
        redis_passwd = config_ptr->getString("redis.passwd");
      }
    }
  }
  if (!redis_add_host(kGuildServiceChatName, redis_host, redis_port,
                      redis_user, redis_passwd)) {
    LOG_FAIL("公会聊天服务启动失败");
    return false;
  }

  if (!common::singleton_start<common::util>(context)) {
    LOG_FAIL("公会聊天服务启动失败");
    return false;
  }

  return true;
}

bool GuildServiceChatContext::Uninit() {
  return common::singleton_stop<common::service_redis_client>() &&
         common::singleton_stop<common::util>() &&
         common::singleton_stop<common::service_context>() &&
         common::singleton_stop<common::service_logger>();
}

void GuildServiceChatContext::Tick(time_t ms) {
  common::singleton_update<common::service_redis_client>(ms);
}

};  // namespace guild_service